import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class num637 {
    public List<Double> averageOfLevels(TreeNode root) {
        //层序遍历求每层平均值
        List<Double> average = new ArrayList<>();//保存每层的平均值
        Deque<TreeNode> queue = new LinkedList<>();//用队列按层遍历
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            Double sum = 0.0;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                sum += node.val;
                if(node.left != null) {
                    TreeNode left = node.left;
                    queue.offer(left);
                }
                if(node.right != null) {
                    TreeNode right = node.right;
                    queue.offer(right);
                }
            }
            average.add(sum / size);
        }
        return average;
    }
}
